package com.sloth.service.impl;

import com.sloth.mapper.*;
import com.sloth.pojo.*;
import com.sloth.service.PlaceAnOrderService;
import com.sloth.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author lai
 * @time 2021/10/8 9:36
 */
@Service
public class PlaceAnOrderServiceImpl implements PlaceAnOrderService {

    @Autowired
    private MyorderMapper myorderMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Autowired
    private FlowMapper flowMapper;


    @Override
    public ServerResponse insert(Myorder myorder) {
        int rows = myorderMapper.insert(myorder);
        if (rows > 0)
            return ServerResponse.saveSuccess(rows);
        return ServerResponse.saveFail(null);
    }

    @Override
    public ServerResponse getByCustomerIdAddress(Integer customerId) {

        AddressExample example = new AddressExample();
        example.createCriteria().andCustIdEqualTo(customerId);

        List<Address> addressList = addressMapper.selectByExample(example);

        // 新创建一个 收货地址集合，接收除了第一个地址以外的其他收货地址
        List<Address> otherAddress = new ArrayList<>();

        for (int i=0;i<addressList.size();i++){
            if (i > 0){
                otherAddress.add(addressList.get(i));
            }
        }

        return ServerResponse.getSuccess(otherAddress);
    }

    @Override
    public ServerResponse getByCarProductId(Map<Integer,Integer> map) {

        // 用来存放 商品对象 及其 对应的商品id 的数量的 VO 的集合
        List<ProductAndCountVO> productAndCountVOArrayList = new ArrayList<>();
        System.out.println("map map map: " + map);

        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer, Integer> next = iterator.next();

            // 创建一个 商品对象及其对应的商品id的数量的VO
            ProductAndCountVO productAndCountVO = new ProductAndCountVO();
            Product product = productMapper.selectByPrimaryKey(next.getKey());
            productAndCountVO.setProduct(product);
            productAndCountVO.setProductCount(next.getValue());
            productAndCountVOArrayList.add(productAndCountVO);
        }

        return ServerResponse.getSuccess(productAndCountVOArrayList);
    }

    // 查询并返回第一个收货地址
    @Override
    public ServerResponse getByCustomerIdAddressFirst(Integer customer) {
        AddressExample example = new AddressExample();
        example.createCriteria().andCustIdEqualTo(customer);
        Address address = addressMapper.selectByExample(example).get(0);

        return ServerResponse.getSuccess(address);
    }

    // 返回订单的总价格
    @Override
    public Double getMyOrderTotalPrice(Map<Integer, Integer> map) {

        // 订单总价格
        Double myOrderTotalPrice = 0.00;

        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer, Integer> next = iterator.next();
            Product product = productMapper.selectByPrimaryKey(next.getKey());
            Double count = 1.00 * next.getValue();
            myOrderTotalPrice += product.getProPrice() * count;
        }

        return myOrderTotalPrice;
    }


    /**
     * 用于调用支付宝，向支付宝传递 订单中商品名称（拼接）、订单标号、订单金额
     * @param myOrderId 订单id
     * @return 返回多个商品拼接后的名称
     */
    @Override
    public ALiPayMyOrderProductNameAndCount getByMyOrderIdForProNames(Integer myOrderId) {

        // 创建一个 ALiPayMyOrderProductNameAndCount 类型的对象，这个对象中存放拼接后的商品的名称、订单中商品编号、订单的总价格
        ALiPayMyOrderProductNameAndCount aLiPayMyOrderProductNameAndCount = new ALiPayMyOrderProductNameAndCount();

        // 查找该订单，将订单中的订单编号传进 ALiPayMyOrderProductNameAndCount 对象中
        Myorder myorder = myorderMapper.selectByPrimaryKey(myOrderId);

        // 通过订单id在订单详情表中查询属于这个订单的所有订单详情
        OrderDetailsExample orderDetailsExample = new OrderDetailsExample();
        orderDetailsExample.createCriteria().andOrderIdEqualTo(myOrderId);
        List<OrderDetails> orderDetailsList = orderDetailsMapper.selectByExample(orderDetailsExample);

        // 存放订单中商品的总数量
        Integer productsCount = 0;

        // 通过订单详情表中的商品id，在商品表中查询属于这个订单的所有商品的名称
        StringBuilder builder = new StringBuilder();
        for (OrderDetails orderDetails : orderDetailsList){
            Product product = productMapper.selectByPrimaryKey(orderDetails.getProId());
            builder.append(product.getProName() + "、");

            // 获得订单详情中每个商品的数量，求和
            productsCount += orderDetails.getOdProCount();
        }

        // 将 StringBuilder 类型拼接的订单中包含的商品名称转换为 String 类型的字符串，向支付宝传递
        String productsName = builder.toString();
        String myOrderCount = productsCount.toString();

        // 将获得到的订单中商品名称（拼接）、订单中商品的总数量放入 ALiPayMyOrderProductNameAndCount 中
        aLiPayMyOrderProductNameAndCount.setProductsName(productsName);  // 订单中商品名称
        aLiPayMyOrderProductNameAndCount.setOrderNo(myorder.getOrderNo()); // 订单编号
        aLiPayMyOrderProductNameAndCount.setOrderTotalPrice(myorder.getOrderPrice());  // 订单总价格

        return aLiPayMyOrderProductNameAndCount;
    }

    // 通过订单详情id查询该订单详情
    @Override
    public OrderDetails getByOrderDetailsId(Integer orderDetailId) {

        OrderDetails orderDetails = orderDetailsMapper.selectByPrimaryKey(orderDetailId);

        return orderDetails;
    }

    // 通过该订单详情信息中的订单id查询订单收货地址id，通过地址id在地址表中查询该订单的收货地址信息
    @Override
    public Address getByOrderIdForAddress(Integer orderId) {
        System.out.println("订单id============" + orderId);

        Myorder myorder = myorderMapper.selectByPrimaryKey(orderId);
        System.out.println("下单页面的订单详情记录信息： " + myorder);

        Address address = addressMapper.selectByPrimaryKey(myorder.getAddressId());

        return address;
    }

    // 通过订单详情id查询订单信息
    @Override
    public Myorder getMyOrderIdByOrderDetailId(Integer myOrderId) {

        Myorder myorder = myorderMapper.selectByPrimaryKey(myOrderId);

        return myorder;
    }

    // 通过订单详情中的商品id拿到订单详情中的商品信息
    @Override
    public Product getProductByOrderDetailsProId(Integer productId) {

        Product product = productMapper.selectByPrimaryKey(productId);

        return product;
    }

    // 通过订单详情id查询属于该订单详情的流水信息
    @Override
    public Flow getFlowByOrderDetailId(Integer orderDetailId) {

        FlowExample flowExample = new FlowExample();
        flowExample.createCriteria().andOthers1EqualTo(orderDetailId.toString());

        // 因为订单和订单详情中有没有完成支付的，所以对于流水表的返回值要根据实际情况进行判断
        List<Flow> flowList = flowMapper.selectByExample(flowExample);

        if (flowList.size() > 0){
            Flow flow = flowList.get(0);
            return flow;
        }else {
            return null;
        }
//        Flow flow = flowMapper.selectByExample(flowExample).get(0);
    }


    /*@Override
    public ServerResponse getByCarProductId(Map<String,Object> map) {
//    public ServerResponse getByCarProductId(Integer[] productIdList) {

        List<Product> productArrayList = new ArrayList<>();

        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            Product product = productMapper.selectByPrimaryKey((Integer.parseInt(next.getKey())));
            productArrayList.add(product);
        }

        return ServerResponse.getSuccess(productArrayList);
    }*/
}